<template>
  <view>
    <uni-popup ref="popupRef">
      <view class="popup">
        <uni-forms
          :modelValue="formData"
          :rules="rules"
          label-align="right"
          ref="formRef"
        >
          <uni-forms-item label="图片" name="tempurl" required>
            <!-- <select-one-img :formData="formData" @update:formData="handleUpdateFormData" width="200" ratio="16/9" /> -->
            <!-- 上述代码可以简写成下面这样 -->
            <select-one-img
              v-model:formData="formData"
              :width="200"
              ratio="16/9"
            />
          </uni-forms-item>
          <uni-forms-item label="url" name="url" required>
            <uni-easyinput
              type="text"
              v-model="formData.url"
              placeholder="请输入跳转地址"
            />
          </uni-forms-item>
          <uni-forms-item label="排序" name="sort" required>
            <uni-easyinput
              type="number"
              v-model.number="formData.sort"
              placeholder="请输入排序"
            />
          </uni-forms-item>
          <uni-forms-item
            label="跳转类型"
            name="target"
            style="display: flex; align-items: center"
          >
            <uni-data-checkbox
              v-model="formData.target"
              :localdata="targetOptions"
            />
          </uni-forms-item>
          <uni-forms-item
            label="站外appid"
            :required="formData.target === 'miniProgram'"
            name="appid"
            v-if="formData.target === 'miniProgram'"
          >
            <uni-easyinput
              type="text"
              v-model="formData.appid"
              placeholder="请输入站外appid"
            />
          </uni-forms-item>
          <uni-forms-item
            label="是否启用"
            name="isEnable"
            style="display: flex; align-items: center"
          >
            <switch
              @change="handleEnableChange"
              :checked="formData.checked"
              class="switch-btn"
            />
          </uni-forms-item>
          <uni-forms-item>
            <view class="operate-btn">
              <button type="primary" size="mini" @click="handleSave">
                保存
              </button>
              <button type="warn" size="mini" @click="cancel">取消</button>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>
    </uni-popup>
  </view>
</template>
<script setup>
import { ref, watch ,nextTick} from 'vue';
import selectOneImg from '@/components/select-one-img/select-one-img.vue';
import { showToast, uploadFile } from '@/utils/common';
import { cloudToHttp } from '@/utils/tools';
const activityCloudObj = uniCloud.importObject('admin-activity-obj');
const emit = defineEmits(['getList']);
const props = defineProps({
  type: {
    type: String,
    default: 'add',
  },
  maxSort: {
    type: Number,
    default: 0,
  },
});

const popupRef = ref(null);
const formRef = ref(null);
const formData = ref({
  picurl: '',
  sort: 0,
  url: '',
  target: 'self',
  appid: '',
  checked: true,
  tempurl: '',
});
const rules = ref({
  url: {
    rules: [{ required: true, errorMessage: '请输入跳转地址' }],
    label: '跳转地址',
  },
  sort: {
    rules: [{ required: true, errorMessage: '请输入排序' }],
    label: '排序',
  },
  appid: {
    rules: [{ required: true, errorMessage: '请输入站外appid' }],
    label: '站外appid',
  },
  tempurl: {
    rules: [{ required: true, errorMessage: '请上传图片' }],
    label: '图片',
  },
});
const targetOptions = ref([
  { text: '当前页', value: 'self' },
  { text: '小程序', value: 'miniProgram' },
]);
const open = (item) => {
  console.log("🌺 ~ open ~ item:🌳", item)
  popupRef.value.open();
  if (props.type == 'edit') {
    formData.value = item;
    formData.value.tempurl = item.picurl;
  } else {
    nextTick(() => {
      formData.value.sort = props.maxSort + 1;
    });
  }
};
const close = () => {
  popupRef.value.close();
};
const handleEnableChange = (e) => {
  formData.value.checked = e.detail.value;
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    uni.showLoading({
      title: '加载中',
      mask: true,
    });
    if (
      formData.value.tempurl &&
      formData.value.tempurl != formData.value.picurl
    ) {
      let file = await uploadFile(formData.value.tempurl);
      formData.value.picurl = cloudToHttp(file.fileID);
    }
    let params = { ...formData.value };
    delete params.tempurl;
    console.log('🌺 ~ handleSave ~ params:🌳', params);
    if (props.type == 'edit') {
      delete params.nickname;
    }
    const res =
      props.type == 'add'
        ? await activityCloudObj.bannerAdd(params)
        : await activityCloudObj.bannerUpdate(params);

    if (res.errCode == 0) {
      showToast({
        title: props.type == 'add' ? '添加成功' : '修改成功',
      });
      close();
      emit('getList');
    } else {
      showToast({
        title: res.errMsg,
      });
    }
  } catch (error) {
    console.log('🌺 ~ handleSave ~ error:🌳', error);
  } finally {
    uni.hideLoading();
  }
};
const cancel = () => {
  popupRef.value.close();
};

watch(
  () => formData.value.target,
  (newVal) => {
    if (newVal === 'self') {
      formData.value.appid = '';
    }
  },
  { deep: true }
);

defineExpose({
  open,
  close,
});
</script>

<style scoped lang="scss">
.popup {
  background-color: #fff;
  width: 600px;
  min-height: 200px;
  padding: 30px;
  border-radius: 10px;
}
</style>
